package reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 使用有参构造器实例化对象
 */
public class ReflectDemo3 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        Person p = new Person("范传奇",35);
        System.out.println(p);//Person{name='范传奇', age=35}

        //反射
        Class cls = Class.forName("reflect.Person");
        //通过类对象获取对应的构造器
        Constructor c = cls.getConstructor(String.class,int.class);//不传参就是获取无参构造器
        Object o = c.newInstance("刘苍松",33);//new Person("刘苍松",33)
        System.out.println(o);//Person{name='刘苍松', age=33}
    }
}
